package com.hy.interceptor;
/*
 * @ Date: 2024/5/14 9:42
 * @ Description: 拦截jwt验证
 **/

import com.hy.exception.BizException;
import com.hy.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    private final String TOKEN_HEADER = "authorization";
    private JwtUtils jwtUtils = new JwtUtils();
    // 在目标方法执行之前 执行,return true放行，return false拦截
    //也就是说，只能在preHandle方法中进行拦截，所以只有这个方法有返回值，
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        final String method = request.getMethod();
        if ("OPTIONS".equals(method))
            return false;
        // 获取请求头中的token
        final String authToken = request.getHeader(TOKEN_HEADER);
        if (authToken != null){
            String username = null;
            try {
                username = jwtUtils.getUserNameFromToken(authToken);
            }catch (Exception e){
                throw new BizException("请登录");
            }
            if (jwtUtils.validateToken(authToken,username)){
                return true;
            }
        }else {
            response.getWriter().write("{'code':401,'msg':'未登录'}");
            return false;
        }
        System.out.println("我进来了");
        return true;
    }

    //在目标方法执行之后，视图对象返回之前 执行，可以简单的理解为XxxController方法中return “”之前
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    //在视图对象返回之后--流程都执行完毕后，执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
